﻿using System;
using System.Linq;
using System.Linq.Expressions;
using Maxleaf.EDI.DataAccess.UnitOfWork;
using Maxleaf.EDI.Domain;

namespace Maxleaf.EDI.DataAccess.Repositorys
{
    public class RepositoryBase<TEntity> : IRepository<TEntity> where TEntity : class
    {
        public RepositoryBase()
        {
        }

        public object ToDBNull(object value)
        {
            if (null != value)
            {
                return value;
            }

            return DBNull.Value;
        }

        // Note: Change this to internal
        public IQueryable<TEntity> GetAll(IUnitOfWork unitOfWork)
        {
            return ((EFUnitOfWork)unitOfWork).Context.Set<TEntity>();
        }

        public TEntity GetSingleOrDefault(IUnitOfWork unitOfWork, Expression<Func<TEntity, bool>> predicate)
        {
            return this.GetAll(unitOfWork).SingleOrDefault(predicate);
        }

        public virtual void Add(IUnitOfWork unitOfWork, TEntity obj)
        {
            ((EFUnitOfWork)unitOfWork).Context.Entry(obj).State = System.Data.EntityState.Added;
        }

        public virtual void Update(IUnitOfWork unitOfWork, TEntity obj)
        {
            ((EFUnitOfWork)unitOfWork).Context.Entry(obj).State = System.Data.EntityState.Modified;
        }

        public virtual void Delete(IUnitOfWork unitOfWork, TEntity obj)
        {
            ((EFUnitOfWork)unitOfWork).Context.Entry(obj).State = System.Data.EntityState.Deleted;
        }
    }
}
